package com.neasho.neashoadminv1.web.console.generator

import com.neasho.neashoadminv1.infrastructure.domain.generator.AppTable
import com.neasho.neashoadminv1.infrastructure.domain.generator.AppTableColumn
import com.neasho.neashoadminv1.infrastructure.domain.generator.AppTableView
import com.neasho.neashoadminv1.web.service.generator.GeneratorService
import jakarta.servlet.http.HttpServletResponse
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * 代码生成器
 */
@RestController
@RequestMapping("/console/generator")
class GeneratorController(
    val generatorService: GeneratorService
) {

    val log: org.slf4j.Logger = org.slf4j.LoggerFactory.getLogger(GeneratorController::class.java)

    /**
     * 渲染
     */
    @GetMapping("/render")
    fun render(input: GeneratorRenderSpec, response: HttpServletResponse)  {
        val tables : List<AppTable> = generatorService.queryTables(input)
        val columns: List<AppTableColumn> = generatorService.queryColumns(input)
        val tableColsMap: MutableMap<String, MutableList<AppTableColumn>> = mutableMapOf()
        tables.forEach { tableColsMap[it.tableName] = mutableListOf() }
        val tableMap = tables.associateBy { it.tableName }
        columns.forEach {
            val table = tableMap[it.tableName]
            if (table == null) {
                return@forEach
            }
            tableColsMap[it.tableName]?.add(it)
        }
        val allTables = tables.map {
            AppTableView.of(it).also {
                it.columns = tableColsMap[it.tableName] ?: mutableListOf()
            }
        }
        generatorService.renderTable(allTables, response)
    }

}

class GeneratorRenderSpec(
    val tableNames: List<String>
) {

}